/**
 * tron_rx.cpp
 *
 * This programs listens for ON / OFF bytes and toggles all three output pins.
 *
 * Author: Charles DuHadway
 * email: duhadway@gmail.com
 */

#include "../common.h"

#include <msp430.h>
#include <legacymsp430.h>
#include <stdint.h>

#define ON  CHARLES_ON
#define OFF CHARLES_OFF

#define START_ON 1 

#define TOP_LIGHT    BIT0
#define MIDDLE_LIGHT BIT4
#define BOTTOM_LIGHT BIT5

/**
 * USCI0RX_ISR - USCI UART receive character ISR handler
 *
 * This handler is called whenever a new character arrives on the receive pin.
 */
interrupt(USCIAB0RX_VECTOR) USCI0RX_ISR(void) {
  /**
   * Note: a side effect of reading UCA0RXBUF
   * is the rx interrupt flag is cleared
   */
  uint8_t rx_byte = UCA0RXBUF;

  if (rx_byte == FILLER) {
    return;
  }

  if (rx_byte == ON) {
    P1OUT = (TOP_LIGHT | MIDDLE_LIGHT | BOTTOM_LIGHT);
  }

  if (rx_byte == OFF) {
    P1OUT &= ~(TOP_LIGHT | MIDDLE_LIGHT | BOTTOM_LIGHT);
  }
}

/**
 * Sets up the USCI UART hardware for 9600-8-N-1.
 * P1.1 = RX PIN, P1.2 = TX PIN
 */
void serial_init() {
  P1SEL = BIT1 | BIT2;  // P1.1=RXD, P1.2=TXD
  P1SEL2 = BIT1 | BIT2; // P1.1=RXD, P1.2=TXD

  UCA0CTL1 = 0;		// Resetting to known state (nothing)
  UCA0CTL1 |= UCSSEL_2; // use SMCLK for USCI clock

  UCA0BR0 = 104 & 0xFF;        // 16MHz 9600
  UCA0BR1 = 104 >> 8;          // 16MHz 9600

  UCA0MCTL = 0x1; // UCOS16 = 1 , UCBRS=0,

  UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
  IE2 |= UCA0RXIE;      // Enable USCI0RX_ISR interrupt
}

/**
 * Initializes the serial link, enables interrupts and output pins.
 */
int main(void) {
  WDTCTL = WDTPW + WDTHOLD; // Stop WDT

  BCSCTL1 = CALBC1_8MHZ;
  DCOCTL = CALDCO_8MHZ;

  P1DIR = (TOP_LIGHT | MIDDLE_LIGHT | BOTTOM_LIGHT);
  serial_init();

  __bis_SR_register(GIE);  // Enable interrupts.

  while (1) {
    _BIS_SR(CPUOFF);  // Enter low power mode.
    _NOP();
  }
}
